package com.nio.file;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by fangjicai on 2020/6/4.
 */
public class FileNio {
    public static void main(String[] args) {
        try {
            copyFile("E:\\test\\Natasha.zip","E:\\test\\Natasha2.zip");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

    public static void copyFile(String srcFileName,String dstFileName) throws IOException {
        FileInputStream fis = new FileInputStream(srcFileName);
        FileOutputStream fos = new FileOutputStream(dstFileName);
        FileChannel readChannel = fis.getChannel();
        FileChannel writeChannel = fos.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true){
            buffer.clear();//清空缓存区
            if(readChannel.read(buffer) == -1){//从输入的channel中读取数据到buffer中
                break;
            }
            buffer.flip();//将缓存区游标置于0
            writeChannel.write(buffer);//将缓存中的数据输出Channel中
        }
        fis.close();
        fos.close();
    }
}
